package com.zfy.servicebase.exceptionhandler;

import com.zfy.commonutils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.util.NestedServletException;

/**
 * 统一异常处理类
 */

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(CustomBusinessException.class)
    public R customException(CustomBusinessException e) {
        log.error("自定义异常信息：{}", e.getMessage());
        return R.customError();
    }


    @ExceptionHandler({HttpMessageNotReadableException.class})
    public R httpNotReadableException(HttpMessageNotReadableException e) {
        log.error("Http请求消息序列化异常：{}", e.getMessage());
        log.error("HttpMessageNotReadableException：传入类型错误或没有传参错误！");
        return R.httpError();
    }


    @ExceptionHandler({NoLoginException.class})
    public R noLoginException(NoLoginException e) {
        log.error("用户未登录异常：{}", e.getMessage());
        return R.loginError();
    }

    @ExceptionHandler({TokenErrorException.class})
    public R tokenErrorException(TokenErrorException e) {
        log.error("Token验证错误异常：{}", e.getMessage());
        return R.tokenError();
    }


    @ExceptionHandler({NestedServletException.class, StackOverflowError.class})
    public R stackOverflowException(Exception e) {
        log.error("堆栈溢出错误：{}", e.getMessage());
        return R.error().message("堆栈溢出错误");
    }


    //特定异常
    @ExceptionHandler(ArithmeticException.class)
    @ResponseBody
    public R error(ArithmeticException e){
        e.printStackTrace();
        return R.error().message("执行运算异常处理");
    }

    //自定义异常处理 GuliException
    @ExceptionHandler(GuliException.class)
    @ResponseBody
    public R error(GuliException e){
        log.error(e.getMessage());
        e.printStackTrace();
        return R.error().code(e.getCode()).message(e.getMsg());
    }

    //指定异常
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R error(Exception e){
        e.printStackTrace();
        return R.error().message("执行全局异常处理");
    }


}
